import Taro from '@tarojs/taro'
import data from './data';
import createTimer from './time';

const url = `wss://shuai.axises.fun`;

class CustomSocket {
	public socketOpen: boolean = false
	private lockReConnect: boolean = false
	private reconnectTimer: any = null
	private reconnectCountlimit: number = 0
	private socketUrl: string = url
	private socketTask: Taro.SocketTask
	private callback: (string) => void

	constructor(socketUrl: string = url) {
		this.socketUrl = socketUrl
		// this.connectSocket()
	}

	connect() {
		if (this?.socketOpen) return

		console.log("socket url:", this.socketUrl)
		console.log("检查clientId:", data.clientId)

		const _this = this
		Taro.connectSocket({
			url: _this.socketUrl,
			header: { "token": data.clientId },
			success: (_response: any) => console.log('socket connect success:', _response),
			fail: (e: any) => console.log('socket connect fail:', e)
		}).then((socketTask: Taro.SocketTask) => {
			_this.initGlobalSocketEvent(socketTask)
		});
	}

	initGlobalSocketEvent(socketTask: Taro.SocketTask) {
		console.log('Socket连接成功，开始初始化监听事件...')
		this.socketTask = socketTask;
		this.socketTask.onMessage(({ data }) => {
			this.callback(data)
		})

		const _this = this
		socketTask.onOpen(() => {
			_this.socketOpen = true
			console.log('Socket连接已打开监听...')
		})
		socketTask.onError((e: any) => {
			_this.socketOpen = false
			console.log("WebSocket error", e)
		})
		socketTask.onClose(() => {
			_this.socketOpen = false
			console.log('WebSocket close！')
			_this.reconnectSocket()
		})
	}

	reconnectSocket() {
		console.log('Socket连接已断开，开始重连...')
		if (this.lockReConnect) {
			console.log('当前处于连接锁定状态，不能重连')
			return
		}
		this.lockReConnect = true

		clearTimeout(this.reconnectTimer)
		const _this = this
		if (_this.reconnectCountlimit < 10) {
			_this.reconnectTimer = setTimeout(() => {
				_this.connect()
				_this.lockReConnect = false
			}, 5000)
			_this.reconnectCountlimit++;
		}
	}

	public onSocketMessage(callback: (string) => void) {
		this.callback = callback;
		if (this?.socketOpen) return
		this.connect();
	}

	public sendChatMessage(messages: any, errorCallback: (any) => void = () => { }) {
		if (!this.socketOpen) {
			this.reconnectSocket()
		}

		this.socketTask.send({
			data: JSON.stringify({
				"message": messages,
				"apiKey": data.freeApiKey
			}),
			success: () => {
				console.log('sendSocketMessage succ, 当前消息：', messages)
			},
			fail: (e: any) => {
				console.log('sendSocketMessage fail', e)
				errorCallback && errorCallback(true)
			}
		});
	}

	public sendMjMessage(message: any, errorCallback: (any) => void = () => { }) {
		if (!this.socketOpen) {
			this.reconnectSocket()
		}

		// 中途间隔不能超过3分钟
		let timer = createTimer(3 * 60 * 1000)
		timer.onTimeout(() => {
			console.log('sendSocketMessage timeout', message);
			errorCallback && errorCallback(false);
		})
		timer.start();
		// setTimeout(() => {
		// 	timer.reset();
		// }, 10 * 1000); // 首次10s无响应则立即结束

		this.socketTask.send({
			data: JSON.stringify(message),
			success: () => {
				console.log('sendSocketMessage succ, 当前消息：', message)
				timer.reset()
			},
			fail: (e: any) => {
				console.log('sendSocketMessage fail', e)
				errorCallback && errorCallback(true)
			}
		});

		timer.start(); // 开始计时器
		setTimeout(() => {
			timer.reset(); // 重置计时器
		}, 2000);
	}

	// public checkSocketState() {
	// 	this.socketOpen ? '' : this.reconnectSocket()
	// }

	// public closeSocket() {
	// 	if (this.socketOpen) {
	// 		this.socketTask.close(ni)
	// 	}
	// }

}

export default CustomSocket
